//
//  SHPComposeViewController.swift
//  weibo
//
//  Created by songhuipan on 16/4/23.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit
import SVProgressHUD
class SHPComposeViewController: UIViewController {
    
        override func viewDidLoad() {
        super.viewDidLoad()
           
            setupUI()
            
    }
    /// 懒加载输入文字的控件
    private lazy var textView:SHPTextView = {
        
        let textView = SHPTextView()
        textView.delegate = self
        textView.placeholder = "分享新鲜事~~"
        textView.font = UIFont.systemFontOfSize(19)
        // 开启textView的竖直滑动功能
//        textView.alwaysBounceHorizontal = false
        textView.alwaysBounceVertical = true
        return textView
        
    }()
    /// 懒加载底部控件
    private lazy var bottomToolBar:SHPBottomToolBar = {
        
        let bottomToolBar = SHPBottomToolBar()
        bottomToolBar.closeure = {[weak self] (type:bottomToolBarType) in
            switch type{
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.switchKeyboard()
            case .Add:
                print("+")
            }
            
        }
        return bottomToolBar
    }()
    /// 懒加载表情键盘
    private lazy var emoticonKeyboardView:SHPEmoticon = {
        let view = SHPEmoticon()
        view.frame = CGRectMake(0,0,kScreenWidth,216)
        return view
        
    }()
    /// 显示图片的控件
    private lazy var albumCollectionView:SHPAlbumCollectionView = {
        let albumCollectionView = SHPAlbumCollectionView()
        albumCollectionView.closeure = {
            self.selectImage()
        }
        return albumCollectionView
    }()
        /// 懒加载标题控件
    private lazy var titleLabel :UILabel = {
        
        let lab = UILabel(textColor: UIColor.darkGrayColor(), textFont: 17)
        // 获取用户昵称
        let name = SHPUserAccountViewModel.sharedUserAccount.account?.screen_name ?? ""
        let titleString = "发微博\n\(name)"
        // MARK:创建富文本，设置标题样式
        let attr = NSMutableAttributedString(string: titleString)
        let range = (titleString as NSString).rangeOfString(name)
        // MARK:设置指定文字的颜色和大小
        attr.addAttribute(NSForegroundColorAttributeName, value: ThemeColor, range: range)
        attr.addAttribute(NSFontAttributeName, value:UIFont.systemFontOfSize(13), range: range)
        lab.attributedText = attr
        
        lab.textAlignment = .Center
        lab.numberOfLines = 0
        lab.sizeToFit()
        
        return lab
        
    }()
    // MARK:移除通知观察者，该方法只能在类中实现
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
}
// MARK: - UITextViewDelegate
extension SHPComposeViewController:UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        // 根据textview中是否有文字，决定按钮的可用状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        textView.resignFirstResponder()
        
    }
}
// MARK:打开相册的方法
extension SHPComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        albumCollectionView.addImage(getScaleImage(image, width: 600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    // MARK:压缩图片的方法
    func getScaleImage(image:UIImage,width:CGFloat) -> UIImage{
        let height = image.size.height*width/image.size.width
        // 开启图片上下文
        UIGraphicsBeginImageContext(CGSizeMake(width, height))
        // 将图片渲染到上下文中
        image.drawInRect(CGRectMake(0, 0, width, height))
        // 获得图片
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图片上下文
        UIGraphicsEndImageContext()
        
        return resultImage
    }
}
extension SHPComposeViewController {
    // MARK:切换表情键盘的方法
    func switchKeyboard(){
        if textView.inputView == nil{
            textView.inputView = emoticonKeyboardView
            bottomToolBar.isEmoticon = true
        }else{
            textView.inputView = nil
            bottomToolBar.isEmoticon = false
        }
        textView.reloadInputViews()
        textView.becomeFirstResponder()
    }
    // MARK:点击底部选择图片按钮，打开相册
    func selectImage(){
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            
        }else {
            // 不能打开照相机
            presentViewController(imagePicker, animated: true, completion: nil)
        }
        
    }
    // MARK:监听关闭按钮点击事件
    @objc private func dimiss (){
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK:监听发送按钮点击事件,发送微博
    @objc private func send (){
        
        var result:String = String()
        
        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (dicInfo, range, _) -> Void in
            
            if let att = dicInfo["NSAttachment"] as? SHPTextAttachment{
                result += att.emoticonModel?.chs ?? ""
//                print("-----\(result)")
            }else{
                result += (self.textView.attributedText.string as NSString).substringWithRange(range)
            }
        }
//        print(result)
        if albumCollectionView.images.count != 0 {
            uploadTextAndImageWeibo(result)
        }else{
            updateTextWeibo(result)
        }
    }
        /// 设置界面UI
    private func setupUI () {
        view.backgroundColor = UIColor.whiteColor()
        setupNavigation()
        
        view.addSubview(textView)
        textView.addSubview(albumCollectionView)
        view.addSubview(bottomToolBar)
        // 监听键盘frame值改变的观察者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 监听删除按钮点击发送的通知观察者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonClick", name: "deleteButtonClickNotification", object: nil)
        // 监听不同按钮点击发送通知的观察者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "buttonClick:", name: "buttonClickNotification", object: nil)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        albumCollectionView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(textView).offset(10)
            make.size.equalTo(CGSizeMake(kScreenWidth-20, kScreenWidth-20))
            make.top.equalTo(textView).offset(100)
            
        }
        bottomToolBar.snp_makeConstraints { (make) -> Void in
            make.trailing.leading.bottom.equalTo(view)
            make.height.equalTo(44)
        }
}
    // MARK:监听键盘frame值改变的方法
    func keyboardWillChangeFrame(noti:NSNotification){
        // 获取键盘的frame值
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新bottomToolBar的底部约束,选择键盘的y值是为了实现键盘收回后，下移
        bottomToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - kScreenHeigth)
        }
        // 实现动画，目的实现向上滑动与键盘弹出的效果一致
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    // MARK:收到删除按钮点击通知执行的方法
    func deleteButtonClick(){
        textView.deleteBackward()
    }
    // MARK:收到不同按钮点击发送通知执行的方法
    func buttonClick(noti:NSNotification){
        guard let emoticon = noti.object as? SHPEmoticonModel else{
            return
        }
        if emoticon.isEmoji{
            let code = ((emoticon.code ?? "") as NSString).emoji()
            textView.insertText(code)
            
        }else{
//            textView.setValue((true as Bool), forKeyPath: "placeholderLabel.hidden")
//            textView.text = ""
//            textView.setValue(true, forKeyPath: "placeholderLabel.hidden")
//            textView.setValue(true, forKey: "placeholderLabel.hidden")
            // 获得原先的富文本
            let oldAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            // 获得图片
            let path = "\(emoticon.path ?? "")\(emoticon.png ?? "")"
            let image = UIImage(named: path, inBundle: SHPEmoticonTool.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            // 创建一个文本附件
            let attach = SHPTextAttachment()
            // 给自定义的文本附件赋值
            attach.emoticonModel = emoticon
            attach.image = image
            let height = textView.font!.lineHeight
            attach.bounds = CGRectMake(0, -4, height, height)
            // 创建一个富文本
            let attr = NSAttributedString(attachment: attach)
            
            // 获取光标
            let selectRange = textView.selectedRange
            // 替换选中的富文本
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            // 设置富文本字体大小
            oldAttr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, oldAttr.length))
            // 将新的富文本赋值，赋值后光标的位置会发生改变
            textView.attributedText = oldAttr
//            print(textView.attributedText)
            // 移动光标
            textView.selectedRange = NSMakeRange(selectRange.location + 1, 0)
            // 不能使用下面这种赋值方法，因为光标的位置已经发生了改变
//            textView.selectedRange = NSMakeRange(textView.selectedRange.location + 1, 0)
            // 隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
//            textView.setValue(true, forKeyPath: "placeholderLabel.hidden")

            // 实现发送按钮可以点击
            textViewDidChange(textView)
//            self.textView.delegate?.textViewDidChange!(textView)


        }
        
    }
        /// 设置导航栏
    private func setupNavigation () {
        // 设置导航栏左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dimiss")
        // 设置导航栏右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        // 初始状态为不可用
        navigationItem.rightBarButtonItem?.enabled = false
        // 设置导航栏标题view
        navigationItem.titleView = titleLabel
    }
}
extension SHPComposeViewController{
    // MARK:发送一条文字和图片微博的方法
    func uploadTextAndImageWeibo(status:String){
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = ["access_token":SHPUserAccountViewModel.sharedUserAccount.account!.access_token!,
            "status":status
        ]
        
        NetworkTools.sharedTools.POST(urlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            for i in self.albumCollectionView.images{
                
                let data = UIImagePNGRepresentation(i)!
                formData.appendPartWithFileData(data, name: "pic", fileName: "hahah", mimeType: "image/jpeg")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                SVProgressHUD.showSuccessWithStatus("发送成功了")
            }) { (_, error) -> Void in
                SVProgressHUD.showErrorWithStatus("发送失败了")
        }

        
    }
    // MARK:发送一条文字微博的方法
    func updateTextWeibo(status:String){
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let params = ["access_token":SHPUserAccountViewModel.sharedUserAccount.account!.access_token!,
                "status":status
        ]
        NetworkTools.sharedTools.loadData(httpMethod.POST, urlString: urlString, params: params) { (responseObject, error) -> () in
                
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发送失败了")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功了")
        }
    }
}






















